package com.si.anddos;

import java.util.Timer;
import java.util.TimerTask;

import com.si.anddos.dpadapters.AnddosDbAdapter;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Looper;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

/**
 * A class representing Download List activity in anddos application
 * 
 * @author Carlos Martinez
 * 
 */

public class DownloadListActivity extends OptionsMenuActivity {
	private static final int DOWNLOAD_CREATE = 0;
	private static final int ACTIVITY_DETAIL = 1;

	private AnddosDbAdapter mDbHelper;
	private ListView listDownloads;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_list);
		setTitle(R.string.titleDownloadList);

		listDownloads = (ListView) findViewById(R.id.listDownloads);
		listDownloads.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(parent.getContext(),
						DownloadDetailActivity.class);
				i.putExtra(AnddosDbAdapter.colDownloadID, id);
				startActivityForResult(i, ACTIVITY_DETAIL);
			}
		});

		// filling the list from database
		mDbHelper = new AnddosDbAdapter(this);

		fillData();
	}

	private void fillData() {
		class StatusBinder implements SimpleCursorAdapter.ViewBinder {

			boolean retval = false;

			// @Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {

				if (columnIndex == cursor
						.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadStatus)) {
					TextView text = (TextView) view;
					int stat = cursor
							.getInt(cursor
									.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadStatus));
					if (stat == AnddosDbAdapter.StatusWaiting) {
						// yellow text
						text.setTextColor(0xffffff00);
						text.setText(" Waiting");
					} else if (stat == AnddosDbAdapter.StatusProcessing) {
						// blue text
						text.setTextColor(0xff0000ff);
						text.setText(" Processing");
					} else if (stat == AnddosDbAdapter.StatusError) {
						// red text
						text.setTextColor(0xffff0000);
						text.setText(" Error");
					} else if (stat == AnddosDbAdapter.StatusDone) {
						// green text
						text.setTextColor(0xff00ff00);
						text.setText(" Done");
					} else if (stat == AnddosDbAdapter.StatusStopped) {
						// green text
						text.setTextColor(0xff888888);
						text.setText(" Stopped");
					}
					;
					retval = true;
				}
				if (columnIndex == cursor
						.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadFilename)) {
					TextView text = (TextView) view;
					text.setText(cursor.getString(cursor
							.getColumnIndexOrThrow(AnddosDbAdapter.colDownloadFilename)));
					retval = true;
				}
				if (columnIndex == cursor
						.getColumnIndexOrThrow(AnddosDbAdapter.colAccountUsername)) {
					TextView text = (TextView) view;
					text.setText(cursor.getString(cursor
							.getColumnIndexOrThrow(AnddosDbAdapter.colAccountUsername)));
					retval = true;
				}
				return retval;
			}
		}

		mDbHelper.open();
		// Get all of the rows from the database and create the item list
		Cursor downloadsCursor = mDbHelper.getAllDownloads();
		startManagingCursor(downloadsCursor);

		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { AnddosDbAdapter.colDownloadStatus,
				AnddosDbAdapter.colDownloadFilename,
				AnddosDbAdapter.colAccountUsername };

		// and an array of the fields we want to bind those fields to
		int[] to = new int[] { R.id.textDownloadRowStatus,
				R.id.textDownloadRowFileName, R.id.textDownloadRowAccUsername };

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter downloads = new SimpleCursorAdapter(this,
				R.layout.download_list_row, downloadsCursor, from, to);

		downloads.setViewBinder(new StatusBinder());
		// make message to user if no downloads is in database
		if (downloads.getCount() == 0)
			Toast.makeText(this, R.string.textNoDownloads, Toast.LENGTH_SHORT)
					.show();
		listDownloads.setAdapter(downloads);

		registerForContextMenu(listDownloads);

		mDbHelper.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// add new menu item to Options menu - other items are defined in
		// OptionsMenuActivity
		menu.add(0, Globals.NEWDOWNLOAD_ID, 0, R.string.menuNewDownload)
				.setIcon(android.R.drawable.ic_menu_add);
		return true;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// handling click to new account menu item
		switch (item.getItemId()) {
		case Globals.NEWDOWNLOAD_ID:
			createDownload();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// create context menu for delete account
		menu.add(0, Globals.DELETEDOWNLOAD_ID, 0, R.string.menuDeleteDownload);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// handling click to delete account
		switch (item.getItemId()) {
		case Globals.DELETEDOWNLOAD_ID:
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
					.getMenuInfo();
			mDbHelper.open();
			mDbHelper.deleteDownload(info.id);
			mDbHelper.close();
			fillData();
			return true;
		}
		return super.onContextItemSelected(item);
	}

	private void createDownload() {
		// start new account activity for result
		Intent i = new Intent(this, DownloadNewActivity.class);
		startActivityForResult(i, DOWNLOAD_CREATE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		// refill data when goes back from new account activity and cancel
		// button was not pressed
		if (resultCode != RESULT_CANCELED)
			fillData();
	}

	public void onResume() {
		super.onResume();
		fillData();
		/*Timer autoUpdate = new Timer();
		autoUpdate.schedule(new TimerTask() {

			@Override
			public void run() {
				//fillData();
			}
		}, 0, 10000);*/
	}
}